package com.course.cdspringboot.controller.achievement;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.course.cdspringboot.entity.achievement.AchievementAcademicExchange;
import com.course.cdspringboot.entity.achievement.AchievementPatent;
import com.course.cdspringboot.entity.achievement.Achievements;
import com.course.cdspringboot.mapper.achievement.AchievementAcademicExchangeMapper;
import com.course.cdspringboot.mapper.achievement.AchievementsMapper;
import com.course.cdspringboot.security.RoleAccessControl;
import com.course.cdspringboot.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@CrossOrigin
@RestController
@RequestMapping("/api/achievement/academic-exchange")
public class AchievementAcademicExchangeController {

    @Autowired
    RoleAccessControl roleAccessControl;

    @Autowired
    AchievementsMapper achievementsMapper;

    @Autowired
    AchievementAcademicExchangeMapper achievementAcademicExchangeMapper;

    // 搜索成果
    @GetMapping("/search")
    List<AchievementAcademicExchange> searchPaper(@RequestParam  Map<String, Object> params){
//        System.out.println(params);
        if (params.isEmpty()) return null;
        // 角色访问控制
        Long uid = roleAccessControl.checkAccess("ROLE_STUDENT");

        // 根据查询条件获取成果id
        QueryWrapper<Achievements> achievementsQueryWrapper = new QueryWrapper<>();
        achievementsQueryWrapper.eq("owner", uid);
        achievementsQueryWrapper.eq("achievement_type_id", 3);
        if (params.get("reviewStatusId") != null) achievementsQueryWrapper.eq("review_status_id", params.get("reviewStatusId"));
        if (params.get("dateRangeStart") != null && params.get("dateRangeEnd") != null) {
            achievementsQueryWrapper.between("created_date", params.get("dateRangeStart"), params.get("dateRangeEnd"));
        }
        List<Achievements>  achievementsList= achievementsMapper.selectList(achievementsQueryWrapper);
        // 从实体类中筛选成果id
        List<Integer> ids = achievementsList.stream()
                .map(Achievements::getAchievementId)
                .collect(Collectors.toList());

        if (ids.isEmpty()) return null;
//        System.out.println(achievementAcademicExchangeMapper.selectByAchievementIds(ids));

        return achievementAcademicExchangeMapper.selectByAchievementIds(ids);
    }

    // 查询学生学术交流
    @GetMapping("")
    List<AchievementAcademicExchange> getAcademicExchange() {
        // 角色访问控制
        Long uid = roleAccessControl.checkAccess("ROLE_STUDENT");

        // 获取用户所有学术交流的成果id
        List<Integer> ids = achievementsMapper.getAchievementIdsByUser(uid, 3);
        if (ids.isEmpty()) return null;

        // 获取学术交流
//        QueryWrapper<AchievementAcademicExchange> queryWrapper = new QueryWrapper<>();
//        queryWrapper.in("achievement_id", ids);
        return achievementAcademicExchangeMapper.selectByAchievementIds(ids);
    }

    // 学生插入学术交流
    @Transactional
    @PostMapping("")
    public Result addAcademicExchange(@RequestBody AchievementAcademicExchange achievementAcademicExchange) {
//        System.out.println(achievementAcademicExchange);
        // 角色访问控制
        Long uid = roleAccessControl.checkAccess("ROLE_STUDENT");

        // 判断成果名是否重复
        if (achievementAcademicExchangeMapper.countByExchangeName(achievementAcademicExchange.getReportName()) > 0) {
            return Result.insert_error().data("msg", "成果名称重复");
        }

        // 在Achievements 表中插入成果
        Map<String, Object> insert_info = new HashMap<>();
        insert_info.put("owner", uid);
        insert_info.put("achievement_type_id", 3);
        insert_info.put("achievement_id", 0);
        achievementsMapper.insertAchievements(insert_info);

        // 在学术交流表中插入学术交流
        achievementAcademicExchange.setAchievementId((int) insert_info.get("achievement_id"));
        achievementAcademicExchangeMapper.insert(achievementAcademicExchange);
        return Result.insert_ok();
    }

    // 学生更新学术交流
    @PutMapping("")
    public Result updateAcademicExchange(@RequestBody AchievementAcademicExchange achievementAcademicExchange) {
        // 角色访问控制
        Long uid = roleAccessControl.checkAccess("ROLE_STUDENT");

        // 判断是否已经通过审核
        if (achievementsMapper.isAchievementPassed(achievementAcademicExchange.getAchievementId()) > 0) {
            return Result.update_error().data("msg", "审核已通过，无法修改");
        }

        // 判断成果名是否重复
        if (achievementAcademicExchangeMapper.countByExchangeName(achievementAcademicExchange.getReportName()) > 0) {
            return Result.update_error().data("msg", "成果名称重复");
        }

        // 查看学生是否拥有这个成果
        if (achievementsMapper.isUserOwnAchievement(uid, achievementAcademicExchange.getAchievementId()) == 0) {
            return Result.update_error().data("msg", "未拥有此成果");
        }

        // 更新成果
        achievementAcademicExchangeMapper.updateById(achievementAcademicExchange);
        return Result.update_ok();
    }

    // 学生删除学术交流
    @DeleteMapping("")
    public Result deleteAcademicExchange(@RequestBody Map<String, Object> data) {
        // 角色访问控制
        Long uid = roleAccessControl.checkAccess("ROLE_STUDENT");
        int achievementId = (int) data.get("achievementId");

        // 查看学生是否拥有这个成果
        if (achievementsMapper.isUserOwnAchievement(uid, achievementId) == 0) {
            return Result.delete_error().data("msg", "未拥有此成果");
        }

        // 逻辑删除成果
        achievementsMapper.deleteAchievement(achievementId);
        return Result.delete_ok();
    }
}
